package weatherwidget.isrefluxer.bird.com.birdweatherwidget.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.widget.RemoteViews;

import weatherwidget.isrefluxer.bird.com.birdweatherwidget.R;
import weatherwidget.isrefluxer.bird.com.birdweatherwidget.WeatherWidget;
import weatherwidget.isrefluxer.bird.com.birdweatherwidget.constant.WeatherConstant;
import weatherwidget.isrefluxer.bird.com.birdweatherwidget.data.DatabaseHelper;
import weatherwidget.isrefluxer.bird.com.birdweatherwidget.until.DateUtil;
import weatherwidget.isrefluxer.bird.com.birdweatherwidget.until.LogUtil;

/**
 * 项目名称：BirdWeatherWidget
 * 类描述：
 * 创建人：Administrator
 * 创建时间：2016/11/19 11:46
 * 修改人：Administrator
 * 修改时间：2016/11/19 11:46
 * 修改备注：
 */
public class UpdateService extends Service {
    private static final String TAG = "UpdateService";
    LocationController locationController;
    Handler handler;
    WeatherWidget weatherWidget = WeatherWidget.getInstance();
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            LogUtil.log(TAG,"broadcastReceiver: "+action);
            if(WeatherConstant.ACTION_WEATHER_UPDATE.equals(action))
            {
                String city = intent.getStringExtra("city");
                LogUtil.log(TAG,"city: "+city);
                if(TextUtils.isEmpty(city))
                {
                    locationController.startLocation(false);
                    WeathersManager.updateAll(UpdateService.this);

                }else{
                    String isLocal = intent.getStringExtra("isLocal");
                    if (TextUtils.isEmpty(isLocal)) {
                        isLocal = "0";
                    }
                    WeathersManager.updateCity(UpdateService.this, city,
                            isLocal);

                }
            } else if (WeatherConstant.ACTION_MORNCLOUD_LOCATION_SUCCESS
                    .equals(action)){
                String city = intent.getStringExtra("city");
                String localCity = DatabaseHelper
                        .getLocalCity(UpdateService.this);
                LogUtil.log(TAG,"localcity: "+localCity);
                if (!city.equals(localCity)) {
                    WeathersManager.updateCity(UpdateService.this, city, "1");
                }
                weatherWidget.locationSuccess(context, city);
            }else if (WeatherConstant.ACTION_MORNCLOUD_LOCATION_UPDATE
                    .equals(action)) {
                locationController.startLocation(intent.getBooleanExtra(
                        WeatherConstant.DATA_ACTIVE_FRESH_LOCATION, false));
            }else if (WeatherConstant.ACTION_MORNCLOUD_LOCATION_FAILURE
                    .equals(action)) {
                weatherWidget.locationFailure(context, intent.getBooleanExtra(
                        WeatherConstant.DATA_ACTIVE_FRESH_LOCATION, false));
            }else if (WeatherConstant.ACTION_MORNCLOUD_WIDGET_CLICK_FRESH_WEATHER
                    .equals(action)) {
                weatherWidget.freshClick(context);
            }else if (WeatherConstant.ACTION_WEATHER_UPDATE_SUCCESS
                    .equals(action)) {
                String city = intent.getStringExtra("city");
                LogUtil.log(TAG,"receiver(ACTION_WEATHER_UPDATE_SUCCESS): "+city);
                LogUtil.log(TAG,"isLocal: "+DatabaseHelper.isLocalCity(context, city));
                if (DatabaseHelper.isLocalCity(context, city)) {
                    updateWidgetViews(context);
                }
            }else if (WeatherConstant.ACTION_WEATHER_UPDATE_FAILURE
                    .equals(action)) {
                updateWidgetViews(context);
            } else if (WeatherConstant.ACTION_WEATHER_UPDATE_NULL
                    .equals(action)) {
                updateWidgetViews(context);
            } else if (WeatherConstant.ACTION_WEATHER_TIME_UPDATE
                    .equals(action)) {
                updateWidgetViews(context);
            }else if (WeatherConstant.ACTION_WEATHER_NIGHT_UPDATE
                    .equals(action)) {
                updateWidgetViews(context);
            } else if (WeatherConstant.ACTION_WEATHER_INIT_UPDATE.equals(action)) {
                updateWidgetViews(context);
                cancelBroadCast(context);
                updateWeatherByFreq();
                updateTimeBroadCast(context);
            }
        }
    };
    private void cancelBroadCast(Context context) {
        AlarmManager alarm = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(WeatherConstant.ACTION_WEATHER_TIME_UPDATE);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarm.cancel(pendingIntent);

        intent = new Intent(WeatherConstant.ACTION_WEATHER_UPDATE);
        pendingIntent = PendingIntent.getBroadcast(this, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarm.cancel(pendingIntent);

        intent = new Intent(WeatherConstant.ACTION_WEATHER_NIGHT_UPDATE);
        pendingIntent = PendingIntent.getBroadcast(this, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarm.cancel(pendingIntent);
    }
    private void updateWidgetViews(Context context) {
        RemoteViews views = new RemoteViews(context.getPackageName(),
                R.layout.weather_widget);
        weatherWidget.updateViews(context, views);
        ComponentName provider = new ComponentName(context, WeatherWidget.class);
        AppWidgetManager.getInstance(context).updateAppWidget(provider, views);
    }
    @Override
    public void onCreate() {
        super.onCreate();
        LogUtil.log(TAG,"onCreate");
        registerReceiver();
        handler = new Handler();
        locationController = LocationController.getInstance(this, handler);
        updateWeatherByFreq();
        updateTimeBroadCast(this);
    }

    private void updateTimeBroadCast(Context context) {
       Intent intent = new Intent(WeatherConstant.ACTION_WEATHER_TIME_UPDATE);
       PendingIntent pendingIntent = PendingIntent.getBroadcast(context,0,
               intent,PendingIntent.FLAG_UPDATE_CURRENT);
        long updateTimes = System.currentTimeMillis()+ DateUtil.getTimeToNextDay()+5 * 1000;;
        AlarmManager alarmManger = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        alarmManger.setRepeating(AlarmManager.RTC,updateTimes,24*60*60*1000,pendingIntent);
        intent = new Intent(WeatherConstant.ACTION_WEATHER_NIGHT_UPDATE);
        pendingIntent = PendingIntent.getBroadcast(context,0,intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        updateTimes = System.currentTimeMillis()+DateUtil.getTimeToNight() + 5 * 1000;
        alarmManger.setRepeating(AlarmManager.RTC,
                updateTimes,12*60*60*1000,pendingIntent);

    }

    private void updateWeatherByFreq() {
        Intent intent = new Intent(WeatherConstant.ACTION_WEATHER_UPDATE);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,
                intent,PendingIntent.FLAG_UPDATE_CURRENT);
        long updateTimes = System.currentTimeMillis() + 1000;
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC,updateTimes,
        WeatherConstant.UPDATE_FREQUENCY_TIME,pendingIntent);
    }

    private void registerReceiver(){
        IntentFilter intentFilter = new IntentFilter(WeatherConstant.ACTION_WEATHER_UPDATE);

        intentFilter.addAction(WeatherConstant.ACTION_MORNCLOUD_LOCATION_SUCCESS);
        intentFilter.addAction(WeatherConstant.ACTION_WEATHER_UPDATE_SUCCESS);
        registerReceiver(broadcastReceiver, intentFilter);

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
